<template>
  <div>
    <p v-truncate="20" class="scroll-text" @mouseover="startScroll" @mouseout="stopScroll" :data-scrolling="isScrolling" :data-text="originalText">
    <span v-show="!isScrolling">{{ originalText }}</span>
    </p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      originalText: '这是一个非常长的字符串，可能会超出显示区域，需要进行截断处理。',
      isScrolling: false,
    };
  },
  directives: {
    truncate: {
      inserted(el, binding) {
        const maxLength = binding.value;
        const text = el.innerText;
        if (text.length > maxLength) {
          el.innerText = text.slice(0, maxLength) + '...';
        }
      }
    }
  },
  methods: {
    startScroll() {
      this.isScrolling = true;
    },
    stopScroll() {
      this.isScrolling = false;
    }
  }
};
</script>
<style>
.scroll-text {
  width: 200px; /* 设置容器宽度 */
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 显示省略号 */
  position: relative;
  cursor: pointer; /* 鼠标悬停时显示指针 */
}

.scroll-text:hover {
  overflow: visible;
}

.scroll-text::after {
  content: attr(data-text);
  position: absolute;
  top: 0;
  left: 100%;
  white-space: nowrap;
  animation: scroll-left 10s linear infinite;
  opacity: 0;
}

@keyframes scroll-left {
  0% {
    left: 100%;
    opacity: 0;
  }
  5% {
    opacity: 1;
  }
  95% {
    opacity: 1;
  }
  100% {
    left: -100%;
    opacity: 0;
  }
}

.scroll-text[data-scrolling="true"]::after {
  animation-play-state: running;
}

.scroll-text[data-scrolling="false"]::after {
  animation-play-state: paused;
}
</style>